package com.spukmk3me.io;

import java.io.IOException;
import java.io.InputStream;

/* $if SPUKMK3ME_DEBUG$ */
import com.spukmk3me.debug.Logger;
/* $endif$ */
import com.spukmk3me.util.ReferenceCounted;

public abstract class FileHandle extends ReferenceCounted
{
    protected FileHandle( String path, byte location, FileSystem fSystem )
    {
        m_path          = path;
        m_location      = location;
        m_fileSystem    = fSystem;
        
        m_state     = STATE_READY;
    }
    
    /* $if SPUKMK3ME_DEBUG$ */
    @Override
    public String toString()
    {
        return m_path + ' ' + LOCATION_MESSAGE[ m_location ];
    }
    /* $endif$ */
    
    public String getPath()
    {
        return m_path;
    }
    
    public String getParentDirectory()
    {
        int index = m_path.lastIndexOf( '/' );
        
        if ( index == -1 )
            return "";
        
        return m_path.substring( 0, index ); 
    }

    public byte getLocation()
    {
        return m_location;
    }

    public byte getState()
    {
        return m_state;
    }
    
    public InputStream openFileForReading() throws IOException
    {
        if ( getState() == STATE_READY )
        {
            m_openingInputStream = openInputStream();
            
            if ( m_openingInputStream == null )
                return null;
            
            return m_openingInputStream;
        }
        
        return null;
    }
    
    public abstract boolean exists();
    
    @Override
    protected final void onZeroCounter()
    {
        if ( m_state == STATE_OPENING )
        {
            try
            {
                m_openingInputStream.close();
            } catch ( IOException e ) {
                /* $if SPUKMK3ME_DEBUG$ */
                Logger.log( "Error while closing file: --" + m_path + "-- " + LOCATION_MESSAGE[ m_location ] );
                /* $endif$ */
            }
        }
        
        m_path = null;
        m_state = STATE_REMOVED;
    }
    
    protected abstract InputStream openInputStream() throws IOException;
    
    /* $if SPUKMK3ME_DEBUG$ */
    public static final String[] LOCATION_MESSAGE = {
        "internal",
        "external",
        "remote"
    };
    /* $endif$ */
    
    public static final byte LOC_INTERNAL   = 0;
    public static final byte LOC_EXTERNAL   = 1;
    public static final byte LOC_REMOTE     = 2;
    
    //public static final byte STATE_NULL     = 0;
    public static final byte STATE_READY    = 1;
    public static final byte STATE_OPENING  = 2;
    public static final byte STATE_REMOVED  = 3;
    
    private InputStream m_openingInputStream;
    private FileSystem  m_fileSystem;
    private String      m_path;
    private byte        m_location, m_state;
}
